/********************************************************************
* build credit limit weighted by national credit score distribution
********************************************************************/



clear all
set more off
global proj "/Users/hanyang/tu2"
global dataRoot "${proj}/Data"
global stataRoot   "${proj}/Code/3_Analysis"


*** load a function in the analysis folder to adjust for inflation
do "${stataRoot}/01_programs.do"


** append 2011 to 2015 credit limit data
gen year=.
foreach i of numlist 2011/2015{
	append using "$dataRoot/Clean/cl_score_`i'06"
	replace year = `i' if year==.
}
collapse (sum) creditLimitAmount currentBalanceAmount N, by(cz scorebin year)
replace scorebin = scorebin*10
save "$dataRoot/Clean/cl_11to15_yearXczXscorebin_full", replace


use "$dataRoot/Clean/cl_11to15_yearXczXscorebin_full", clear
sort score
drop if scorebin<400

*** construct national credit score distributioon
bysort year scorebin: egen num_score = sum(N)
bysort year: egen num = sum(N)

gen dist_score = num_score/num

replace creditLimitAmount    = creditLimitAmount/N
replace currentBalanceAmount = currentBalanceAmount/N


**** average credit limit at year X cz level weighted by national credit score distributions
collapse creditLimitAmount currentBalanceAmount [w=dist_score], by(cz year)


** adjust for inflation
rename creditLimitAmount creditlimit_bal
rename currentBalanceAmount current_bal

gen asofdate = year*100+6
adjustInflation

** simple average at cz level
collapse *bal, by(cz)

replace creditlimit_bal = creditlimit_bal/1000
replace current_bal = current_bal/1000
gen avail_credit = creditlimit_bal-current_bal


label var creditlimit_bal "credit limit ($000s)"
label var avail_credit "available credit ($000s)"

*** save cz level covariate
compress
save "$dataRoot/Clean/cz_credit_limit", replace
